from django.shortcuts import render, redirect
from app01.utils.pagination import Pagination
from app01 import models
from app01.utils.form import UpModelForm


def city_list(request):
    """城市列表"""
    queryset = models.City.objects.all()
    page_object = Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "city_list.html", context)


def city_add(request):
    """添加城市"""
    title = "新建城市"
    if request.method == "GET":
        form = UpModelForm()
        return render(request, 'upload_modelform.html', {"title": title, 'form': form})
    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对应文件自动保存
        # 字段+上传路径写入到数据库
        form.save()
        return redirect("/city/list/")
    return render(request, 'upload_modelform.html', {"title": title, 'form': form})
